/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlets;

import gestionnaire.Gestionnaires;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilderFactory;
import modeles.*;

/**
 *
 * @author MAZID
 */
@WebServlet(name = "ServletAdmin", urlPatterns = {"/admin"})
public class ServletAdmin extends HttpServlet {

    @EJB
    private Gestionnaires gestionnaires;

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    public static class AdminException extends Exception {

        String param;

        public AdminException(String message, String param) {
            super(message);
            this.param = param;
        }
    }

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        try {

            // Definir la page principale et l'enregistrer pour les liens générés dans les jsp incluses
            //
            String forwardTo = "admin.jsp";
            String linkTo ="admin?";
            
            request.setAttribute("forwardTo", forwardTo);
            request.setAttribute("linkTo", linkTo);
            
            String action = (String) request.getParameter("action");
            if (action == null || action.equalsIgnoreCase("list_films")) {

                Collection<Film> listeFilms = gestionnaires.getAllFilms();
                request.setAttribute("listeFilms", listeFilms);

                // Definir la page principale
                request.setAttribute("mainInclude", "vues/admin/liste_films.jspf");

            } 
            
            else if (action.equals("edit")) {
                  
                int id = Integer.parseInt(request.getParameter("target"));
                Film film = gestionnaires.getFilm(id);
                
                
                request.setAttribute("film", film);
                
                // Definir la page principale
                request.setAttribute("mainInclude", "vues/admin/edit_film.jspf");
            } 
               
            else if (action.equals("newMovie")) {

                // Obtenir le titre et la decription
                //
                String titre = request.getParameter("nom");
                if (titre == null) {
                    throw new AdminException("Titre inexistant", null);
                }

                String desc = request.getParameter("desc");
                if (desc == null) {
                    throw new AdminException("Description inexistants", null);
                }
                // Obtenir le prix et le stock
                //
                float prix = Float.parseFloat(request.getParameter("prix"));
                int stock = Integer.parseInt(request.getParameter("stock"));


                // Obtenir et rechercher le genre
                //
                int genreId = Integer.parseInt(request.getParameter("gendreId"));
                Genre genre = null;
                for (Genre g : gestionnaires.getAllGenres()) {
                    if (g.getId() == genreId) {
                        genre = g;
                        break;
                    }
                }
                if (genre == null) {
                    throw new AdminException("Genre introuvable", request.getParameter("gendreId"));
                }

                // Obtenir et rechercher l'etat
                //
                int stateId = Integer.parseInt(request.getParameter("stateId"));
                EtatFilm state = null;
                for (EtatFilm i : gestionnaires.getAllEtats()) {
                    if (i.getId() == stateId) {
                        state = i;
                        break;
                    }
                }
                if (state == null) {
                    throw new AdminException("Etat introuvable", request.getParameter("stateId"));
                }

                // Obtenir le realisateur
                //
                int realId = Integer.parseInt(request.getParameter("realId"));
                Realisateur real = null;
                for (Realisateur i : gestionnaires.getAllRealisateurs()) {
                    if (i.getId() == realId) {
                        real = i;
                        break;
                    }
                }
                if (real == null) {
                    throw new AdminException("Realisateur introuvable", request.getParameter("realId"));
                }
                // Obtenir les acteurs
                //
                List<Acteur> actors = new ArrayList<Acteur>();


                // Obtenir l'image
                //
                String img = request.getParameter("img"); //todo: upload

                // Creer le film
                //
                gestionnaires.creerUnFilm(titre, desc, img, prix, genre, real, actors, stock, state);
                //creerUnFilm("Expert1 de Miami","un film qui est sortie le 22 avril 2012","images1.jpg",2.5, genre1,real1, acteursDeCeFilm, 200,promo);


            } else if (action.equals("newRealisator")) {
                String nom = request.getParameter("nom");
                String prenom = request.getParameter("prenom");
                String desc = request.getParameter("desc");
                gestionnaires.creerRealisateur(nom, prenom, desc);

                forwardTo = "index.jsp?action=accueil";
            } else if (action.equals("newGenre")) {

                String nom = request.getParameter("nom");
                gestionnaires.creerGenre(nom);

                forwardTo = "index.jsp?action=accueil";
            } else if (action.equals("newMovieState")) {

                String nom = request.getParameter("nom");
                gestionnaires.creerEtatFilm(nom);

                forwardTo = "index.jsp?action=accueil";
            } else if (action.equals("newActor")) {

                String nom = request.getParameter("nom");
                String prenom = request.getParameter("prenom");
                String desc = request.getParameter("desc");
                gestionnaires.creerActeur(nom, prenom, desc);

                forwardTo = "index.jsp?action=accueil";
            }

            else if (action.equals("tst")) {
                try {
                    String query = "http://api.allocine.fr/rest/v3/search?partner=YW5kcm9pZC12M3M&q=matrix";
                    // javax.xml.parsers.DocumentBuilderFactory
                    URLConnection connection = new URL(query).openConnection();
                    //connection.setRequestProperty("Accept-Charset", charset);
                    InputStream rep = connection.getInputStream();
                    int r = 0;
                    while (r != -1) {
                        r = rep.read();
                        System.out.write(r);
                    }
                    /*
                     * StringWriter writer=new StringWriter(); InputStreamReader
                     * streamReader=new InputStreamReader(rep); //le buffer
                     * permet le readline BufferedReader buffer=new
                     * BufferedReader(streamReader); String line=""; while (
                     * null!=(line=buffer.readLine())){ writer.write(line); } //
                     * Sortie finale dans le String
                     * System.out.println(writer.toString()); //
                     */



                    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                    javax.xml.parsers.DocumentBuilder builder = factory.newDocumentBuilder();
                    org.w3c.dom.Document doc = builder.parse(rep);
                    System.out.println("XML: " + doc.toString());


                } catch (Exception e) {
                    System.err.println(e);
                }
            }


            RequestDispatcher dp = request.getRequestDispatcher(forwardTo);
            dp.forward(request, response);

        } catch (AdminException e) {
            System.err.println(e.getMessage());
        }


    }

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
